package com.seeyon.apps.kkARPEvent.util;

import java.io.BufferedReader;
import java.io.File;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Map;

import com.alibaba.fastjson.JSON;
import com.seeyon.ctp.common.AppContext;
import org.apache.commons.logging.Log;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;

import com.seeyon.ctp.common.log.CtpLogFactory;
import com.seeyon.ctp.util.json.JSONUtil;
import org.apache.http.util.EntityUtils;

@SuppressWarnings("deprecation")
public class FileUploadUtil {

    private static final Log log = CtpLogFactory.getLog(FileUploadUtil.class);
    private static final String URL = AppContext.getSystemProperty("ARPUrl.IP");
    private static final String UPDATE_URL = URL + AppContext.getSystemProperty("ARPUrl.FileUpdate");

    @SuppressWarnings({"unchecked"})
    public static Map<String, Object> uploadFile(String token, File file) {
        CloseableHttpClient httpClient = null;
        try {
            // 构建动态URL
            String uploadUrl = UPDATE_URL;
            log.info("##客开日志: 完整上传URL=" + uploadUrl);

            // 创建MultipartEntity
            MultipartEntity multipartEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
            multipartEntity.addPart("file", new FileBody(file));

            // 配置HTTP请求
            HttpPost request = new HttpPost(uploadUrl);
            //request.setHeader("Authorization", "bearer " + token);
            request.setEntity(multipartEntity);

            httpClient = HttpClients.createDefault();
            HttpResponse response = httpClient.execute(request);
            log.info("##客开日志: 接口请求结果: " + response);
            log.info("##客开日志: 接口返回状态码: " + response.getStatusLine().getStatusCode());

            HttpEntity entity = response.getEntity();
            log.info("##客开日志: 接口返回内容: " + entity);
            if (entity != null) {
                String responseString = EntityUtils.toString(entity, "UTF-8");
                log.info("客开日志-----------【sendPostRequest】响应内容: " + responseString);
                // 将响应字符串解析为 Map
                return JSON.parseObject(responseString, Map.class);
            }
            return null;

            //// 检查状态码
            //int statusCode = response.getStatusLine().getStatusCode();
            //if (statusCode != 200) {
            //    log.error("##客开日志: 接口请求失败，状态码: " + statusCode);
            //    retMap.put("code", "0");
            //    retMap.put("message", "接口请求失败，状态码: " + statusCode);
            //    return retMap;
            //}
            //
            //// 处理响应数据
            //is = response.getEntity().getContent();
            //in = new BufferedReader(new InputStreamReader(is));
            //StringBuilder buffer = new StringBuilder();
            //String line;
            //while ((line = in.readLine()) != null) {
            //    buffer.append(line);
            //}
            //
            //String ret = buffer.toString();
            //log.info("##客开日志: 文件上传返回报文:" + ret);
            //
            //// 判断是否为JSON格式
            //if (!isJSON(ret)) {
            //    log.error("##客开日志: 非JSON格式响应: " + ret);
            //    retMap.put("code", "0");
            //    retMap.put("message", "非JSON格式响应: " + ret);
            //    return retMap;
            //}
            //
            //// 解析JSON
            //retMap = JSONUtil.parseJSONString(ret, Map.class);
            //String flag = (String) retMap.get("flag");
            //if ("SUCCESS".equals(flag)) {
            //    retMap.put("code", "1");
            //    log.info("##客开日志: 文件上传成功，文件ID: " + ((Map) retMap.get("data")).get("id"));
            //} else {
            //    retMap.put("code", "0");
            //    retMap.put("message", retMap.get("msg"));
            //    log.error("##客开日志: 文件上传失败 - " + retMap.get("msg"));
            //}
            //
        } catch (Exception e) {
            log.error("##客开日志: 文件上传异常", e);
            return null;
        }
    }

    private static boolean isJSON(String str) {
        try {
            new com.fasterxml.jackson.databind.ObjectMapper().readTree(str);
            return true;
        } catch (Exception e) {
            return false;
        }
    }


}

